package com.atguigu.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.seckill.feign.CouponFeignService;
import com.atguigu.seckill.feign.ProductFeignClient;
import com.atguigu.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.seckill.service.SeckillService;
import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.seckill.vo.SeckillSessionsWithSkus;
import com.atguigu.seckill.to.SeckillSkuRedisTo;
import com.atguigu.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * description: SeckillServiceImpl
 * date: 2023/1/4 23:01
 * author: MR.孙
 */
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;


    @Autowired
    private RabbitTemplate rabbitTemplate;

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";    //+商品随机码

    @Override
    public void uploadSeckillSkuLatestDays() {

        //1、扫描需要参与秒杀的活动
        R r = couponFeignService.getLates3DaySession();
        if (r.getCode()==0) {
            //上架商品
            List<SeckillSessionsWithSkus> sessions = r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });

            if (sessions!=null && sessions.size()>0) {
                //缓存到redis
                //1、缓存活动信息
                saveSecKillSession(sessions);
                //2、缓存活动的关联商品信息
                saveSecKillSku(sessions);
            }
        }

    }

    public List<SeckillSkuRedisTo> blockHandler(BlockException e){
        System.err.println("getCurrentSeckillSkus资源被限流了" + e);
        return null;
    }

    //返回当前时间可以参与的秒杀商品信息
    @SentinelResource(value = "getCurrentSeckillSkus", blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {

        //确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();

        try(Entry entry = SphU.entry("seckillSkus");) {

            //从redis中获取所有的秒杀场次
            Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            for (String key : keys) {
                //seckill:sessions:1672891200000_1672930800000
                //去除前缀得到秒杀活动开始和结束时间
                String replace = key.replace(SESSION_CACHE_PREFIX, "");

                String[] s = replace.split("_");
                //获取开始时间
                long startTime = Long.parseLong(s[0]);
                long endTime = Long.parseLong(s[1]);
                //根据当前时间的时间戳，判断是否在秒杀场次的时间内
                if (time > startTime && time < endTime) {
                    //获取这个秒杀场次需要的所有商品信息
                    //先根据秒杀场次获取场次和skuId组成的value值，然后根据skuId查到秒杀商品
                    //我们的秒杀场次的值是list，所以可以通过range获取指定区间的值
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    //获取所有秒杀的商品信息
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = hashOps.multiGet(range);
                    if (list!=null && list.size()>0){
                        List<SeckillSkuRedisTo> collect = list.stream()
                                .map(item -> {
                                    SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject((String) item, SeckillSkuRedisTo.class);
                                    return seckillSkuRedisTo;
                                })
                                .collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }

        }catch (BlockException e) {
            System.out.println("资源限流了..." + e.getMessage());
        }

        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //根据skuId去redis查找对应的秒杀商品信息

        //1.找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();

        if (keys!=null && keys.size()>0){
            String regx = "\\d-" + skuId;
            for (String key : keys) {
                //4_33   遍历所有的key找到sku对应的key    ?_skuId
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    //随机码信息是当前参与秒杀活动才能去携带，否则不携带
                    long currentTime = new Date().getTime();
                    //如果当前时间在秒杀场次时间内，就返回随机码
                    if (currentTime >= seckillSkuRedisTo.getStartTime() && currentTime <= seckillSkuRedisTo.getEndTime()) {
                    }else {
                        seckillSkuRedisTo.setRandomCode(null);
                    }
                    return seckillSkuRedisTo;
                }
            }
        }

        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) throws InterruptedException {

        //1、获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isNotEmpty(json)) {
            //校验秒杀等信息合法性
            SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //1. 校验时间的合法性
            long time = System.currentTimeMillis();
            long startTime = seckillSkuRedisTo.getStartTime();
            long endTime = seckillSkuRedisTo.getEndTime();
            if (time>=startTime && time<=endTime) {
                //2. 校验随机码和商品id  redis中的数据与页面传递的数据进行比对
                String randomCode = seckillSkuRedisTo.getRandomCode();//随机码
                Long skuId = seckillSkuRedisTo.getSkuId();
                String killCode = seckillSkuRedisTo.getPromotionSessionId() + "-" + skuId;
                if (randomCode.equals(key) && killCode.equals(killId)) {
                    //3、验证这个人是否已经购买过。 幂等性问题：不希望购买过的人继续购买此秒杀物品；只要秒杀成功，就去站位。 userId_sessionId_skuId
                    MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
                    String redisKey =memberResponseVo.getId() + "-" +killCode;
                    //进入到这里，说明秒杀活动已经开启，所以过期时间应为结束的时间 - 当前时间的差值
                    long ttl = seckillSkuRedisTo.getEndTime() - System.currentTimeMillis();
                    //3.1、通过在redis判断是否秒杀过，通过userId_sessionId_skuId来占位
                    Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);//setnx
                    //占位成功，说明该用户未秒杀过该商品，则继续
                    if (aBoolean) {
                        //4、验证秒杀数量是否合理
                        System.out.println(seckillSkuRedisTo.getSeckillLimit());
                        if (num<=seckillSkuRedisTo.getSeckillLimit()) {
                            //获取秒杀商品的信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + seckillSkuRedisTo.getRandomCode());
                            //尝试秒杀商品num个信号量     注意不要用阻塞的acquire()方法
                            boolean result = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                            if (result) {
                                //秒杀成功
                                //快速下单。发送MQ消息
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                seckillOrderTo.setOrderSn(timeId);
                                seckillOrderTo.setMemberId(memberResponseVo.getId());
                                seckillOrderTo.setNum(num);
                                seckillOrderTo.setPromotionSessionId(seckillSkuRedisTo.getPromotionSessionId());
                                seckillOrderTo.setSkuId(seckillSkuRedisTo.getSkuId());
                                seckillOrderTo.setSeckillPrice(seckillSkuRedisTo.getSeckillPrice());
                                //给订单服务发送秒杀消息
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);
                                return timeId;
                            }
                        }
                    }

                }

            }

        }
        return null;
    }


    private void saveSecKillSession(List<SeckillSessionsWithSkus> sessions) {

        sessions.stream().forEach((session)->{
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime +  "_"  + endTime;
            System.out.println(key);
            if (!redisTemplate.hasKey(key)) {
                //缓存活动信息
                List<String> collect = session.getRelations().stream().map(item ->
                  item.getPromotionSessionId() + "-" + item.getSkuId().toString()
                ).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }

    private void saveSecKillSku(List<SeckillSessionsWithSkus> sessions) {

        //做准备hash操作
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        //缓存商品
        sessions.stream().forEach(session->{
            String token = UUID.randomUUID().toString().replace("-", "");
            session.getRelations().stream().forEach(seckillSkuVo->{
                String key = seckillSkuVo.getPromotionSessionId() + "-" + seckillSkuVo.getSkuId().toString();
                if (!ops.hasKey(key)) {
                    SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
                    //1、sku的基本数据
                    R r = productFeignClient.getSkuInfo(seckillSkuVo.getSkuId());
                    if (r.getCode()==0) {
                        SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        seckillSkuRedisTo.setSkuInfoVo(skuInfo);
                    }

                    //2、sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, seckillSkuRedisTo);

                    //3、 设置上当前商品的秒杀时间信息
                    seckillSkuRedisTo.setStartTime(session.getStartTime().getTime());
                    seckillSkuRedisTo.setEndTime(session.getEndTime().getTime());

                    //4、为商品设置随机码，防止秒杀被人利用脚本攻击 seckill?skuId=1&key=sdsdfdg
                    seckillSkuRedisTo.setRandomCode(token);
                    ops.put(key, JSON.toJSONString(seckillSkuRedisTo));

                    //如果当前这个场次的商品的库存信息已经上架就不需要上架
                    //5、 使用库存作为信号量   限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
            });
        });

    }
}
